package cmd

import (
	"colly/template"
	"fmt"
	"github.com/hibiken/asynq"
	"github.com/spf13/cobra"
	"os"
	"time"
)

func init() {
	recvCmd.PersistentFlags().StringVarP(&proxyFile, "proxy", "p", "", "proxy")
	rootCmd.AddCommand(recvCmd)
}

var recvCmd = &cobra.Command{
	Use:   "recv",
	Short: "This is the recv command",
	Long:  "This is the recv command",
	PreRun: func(cmd *cobra.Command, args []string) {
		if proxyFile == "" {
			Log.Warning("Proxy File Not Found")
			time.Sleep(time.Second * 5)
			os.Exit(0)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		srv := asynq.NewServer(
			asynq.RedisClientOpt{Addr: Cfg.Redis.Addr(), Password: Cfg.Redis.Pass, DB: Cfg.Redis.Db},
			asynq.Config{
				Concurrency: 10,
				RetryDelayFunc: func(n int, e error, t *asynq.Task) time.Duration {
					if t.Type() == template.TypeServerInfo {
						return 120 * time.Second
					}
					return asynq.DefaultRetryDelayFunc(n, e, t)
				},
				Queues: map[string]int{
					"critical": 6,
					"default":  3,
					"low":      1,
				},
			},
		)
		mux := asynq.NewServeMux()
		mux.HandleFunc(template.TypeServerInfo, template.HandleServerTask)
		mux.HandleFunc(template.TypeOfferInfo, template.HandleOfferTask)
		if err := srv.Run(mux); err != nil {
			fmt.Printf("could not run server: %v", err)
		}
	},
}
